package com.yan.test.work.testpaging3.net.response;

import android.text.TextUtils;

import com.google.gson.reflect.TypeToken;
import com.yan.test.work.testpaging3.net.JsonContervUtil;
import com.yan.test.work.testpaging3.net.L;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.Headers;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Create By : 'YWY'
 * On : 2023/9/28
 */
public class AsyncResponseData<T> {

    private final Response response;
    private final Class<T> claz;
    private ResponseModelBean<T> responseModel;

    public ResponseModelBean<T> getResponseModel() {
        return responseModel;
    }

    public AsyncResponseData(Response response , Class<T> claz) {
        this.response = response;
        this.claz = claz;

        if(response == null){
            responseModel = new ResponseModelBean<T>();
            responseModel.resp_code = -1;
            responseModel.isSuccess = false;
            responseModel.total = "FAILURE";
        }else{
            Request request = response.request();

            try {
                if(response.isSuccessful()){
                    onSuccess(request, response);
                }else{
                    onFailure(request, response);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void onSuccess(Request request, Response response) throws IOException {
        Headers headers = response.headers();
        String responseString = response.body().string();
        int statusCode = response.code();
        printResponse(statusCode, request, headers, responseString, null);
        if (TextUtils.isEmpty(responseString)) {
            responseModel = new ResponseModelBean<T>();
            responseModel.resp_code = -1;
            responseModel.isSuccess = false;
            responseModel.total = "SYSTEM_ERROR";
            return;
        }

        JSONObject jsonObject = null;
        JSONObject dataJSONObject = null;
        String successMessage = null;
        try {
            jsonObject = new JSONObject(responseString);
            dataJSONObject = jsonObject.getJSONObject("aloneRestaurantLatestChips");

        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            Type type = new TypeToken<ResponseModelBean<T>>(){}.getType();
            responseModel = JsonContervUtil.jsonToObject(responseString, type);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                String string = jsonObject.optString("data");
                if (!string.substring(0, 1).equals("{")) {
                    successMessage = string;
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        if (jsonObject == null) {
            responseModel = new ResponseModelBean<T>();
            responseModel.isSuccess = false;
            responseModel.resp_code = -1;
            responseModel.total = "SYSTEM_ERROR";
            return;
        }
        boolean success = responseModel.resp_code == 1000;
        responseModel.isSuccess = success;
        // 业务执行成功时
        if (success) {
            if (responseModel == null) {
                responseModel = new ResponseModelBean<T>();
                responseModel.isSuccess = false;
            }

            if (responseModel.articles != null) {
                T result = null;
                try {
                    String dataStr = JsonContervUtil.objectToStr(responseModel.articles);
                    result = JsonContervUtil.jsonToObject(dataStr , claz);
                    responseModel.articles = result;
                } catch (Exception e) {
                    e.printStackTrace();
                    responseModel.articles = null;
                    responseModel.isSuccess = false;
                }
            }else{
                T result = null;
                try {
                    String dataStr = JsonContervUtil.objectToStr(dataJSONObject.toString());
                    result = JsonContervUtil.jsonToObject(dataStr , claz);
                    responseModel.articles = result;
                } catch (Exception e) {
                    e.printStackTrace();
                    responseModel.articles = null;
                }
            }
            if (!TextUtils.isEmpty(successMessage)) {
                responseModel.total = successMessage;
            }

        } else {

            if (responseModel == null) {
                responseModel = new ResponseModelBean<T>();
                responseModel.isSuccess = false;
                responseModel.resp_code = -1;
                responseModel.total = "SYSTEM_ERROR";
            }

//
//            //Token 过期
//            if(responseModel.resp_code == -1001){
//                EventBus.getDefault().post(new BaseMsg("RELOGIN",""));
//            }

            return;
        }
    }





    private void onFailure(Request request, Response response) throws IOException {
        // http请求失败，默认处理
        int statusCode = response.code();
        printResponse(statusCode, request, response.headers(), response.body().string(), new Exception(response.body().toString()));

        responseModel = new ResponseModelBean<T>();
        responseModel.isSuccess = false;
        responseModel.resp_code = -1;
        responseModel.total = "SYSTEM_ERROR";

    }

    private void printResponse(int statusCode, Request request, Headers headers, String responseString, Exception throwable) {
        if (throwable == null) {
            log("------http请求成功------");
        } else {
            log("------http请求失败------");
            log("异常描述：" + throwable.getMessage());
        }
        String requestURI = request.url().toString();
        if (requestURI != null) {
            log("请求地址：" + requestURI.toString());
        }
        log("响应状态码：" + statusCode);
        StringBuffer headerSb = new StringBuffer();
        if (headers != null) {
            for (String key : headers.names()) {
                String headerStr = headers.get(key);
                headerSb.append(key).append("=").append(headerStr).append(";");

            }
        }
        log("响应头：" + headerSb);
        log("响应数据：" + responseString);
    }
    private void log(String msg) {
        L.d(ResponseHandlerBean.class, msg);
    }
}
